﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Lists;
using Vouchers;
using GeneralLibs;
using System.Data.SqlClient;
using BasicForms;
using BarcodeLib;

namespace BarCode
{
    public partial class FrmBarCode : BasicForms.FrmBase
    {
        const int BARCODE_WIDTH = 190;
        const int BARCODE_HEIGHT = 49;
        public double cPrinterWidth, cPrinterHeight;
        int ColsPerPage, RowsPerPage;

        DsPrintBarCode dsPrinBarcode = new DsPrintBarCode();

        public void GetValue(ref int SoCot, ref int SoDong,ref double Widths, ref double Hegihts )
        { 
            SoCot=ColsPerPage;
            SoDong=RowsPerPage;
            Widths=cPrinterWidth;
            Hegihts = cPrinterHeight;
        }
        public FrmBarCode()
        {
            InitializeComponent();
        }
        private void FrmMain_Load(object sender, EventArgs e)
        {
            if (DesignMode) return;

            #region cmbDoiTuong
            cmbDoiTuong.DataSource = DanhMucDoiTuongNghiepVu.GetDanhMucNhaCungCap().DataView;
            cmbDoiTuong.DisplayColumn = "Ten";
            cmbDoiTuong.ValueColumn = "ID";
            cmbDoiTuong.AddVisibleColumn("Ma", "Mã");
            cmbDoiTuong.AddVisibleColumn("Ten", "Tên");
            #endregion     

            #region cmbNhomHang
            cmbNhomHang.DataSource = DanhMucNhomVatTuHangHoa.GetAll().DataView;
            cmbNhomHang.DisplayColumn = "Ten";
            cmbNhomHang.ValueColumn = "ID";
            cmbNhomHang.AddVisibleColumn("Ma", "Mã");
            cmbNhomHang.AddVisibleColumn("Ten", "Tên");
            #endregion 

            //CbPaperStyle.SelectedIndex = 1;
            //CbDonVi.SelectedIndex = 0;
            //for (int i = 0; i < RowsPerPage * ColsPerPage; i++)
            //{
            //    CbStartAt.Items.Add(i);
            //}
            //CbStartAt.SelectedIndex = 0;

            //numSoLuongIn.Value = 1;
            DgrInHang.DataSource = dsPrinBarcode.ChoosedHang;

            if (!RdoTheoPhieuNhap.Checked && !RdoToanBoKhoHang.Checked)
            {
                txtFindMa.Enabled = false;
                TxtFindName.Enabled = false;
            }
        }

        private void TxtBarCode_TextChanged(object sender, EventArgs e)
        {
        }
       
        private void DgrHangHoa_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            TxtBarCode.Text = DgrHangHoa["Ma", DgrHangHoa.CurrentRow.Index].Value.ToString();
            TxtBookName.Text = DgrHangHoa["Ten", DgrHangHoa.CurrentRow.Index].Value.ToString();
            if (TxtBarCode.Text != "") TxtTopText.Text = DanhMucVatTuHangHoa.GetByMa(TxtBarCode.Text.ToString()).TenNganGon;
            TxtBottomText.Text = string.Format("{0:0,0}", Decimal.Parse((DgrHangHoa["GiaBia", DgrHangHoa.CurrentRow.Index].Value.ToString())));
            //LbBottom.Text = "Giá: " + string.Format("{0:0,0}", Decimal.Parse((DgrHangHoa["GiaBia", DgrHangHoa.CurrentRow.Index].Value.ToString()))); 
            //if(DgrHangHoa["Ten", DgrHangHoa.CurrentRow.Index].Value.ToString().Length>50)
            //{
            //    LbTop.Text = DgrHangHoa["Ten", DgrHangHoa.CurrentRow.Index].Value.ToString().Substring(0, 50);  
            //}
            //if (RdoToanBoKhoHang.Checked == true)
            //{
            //    numSoLuongIn.Value = 1;
            //}
            //else
            //{
            //    numSoLuongIn.Value = (decimal)DgrHangHoa[3, DgrHangHoa.CurrentRow.Index].Value;
            //}          
        }

        private void RdoToanBoKhoHang_CheckedChanged(object sender, EventArgs e)
        {
            if (RdoToanBoKhoHang.Checked)
            {
                DanhMucVatTuHangHoa.Instance.DataView.Table.DefaultView.Sort = "Ten";
                DgrHangHoa.DataSource = Lists.DanhMucVatTuHangHoa.Instance.DataView;
                TxtFindName.Focus();
                DgrHangHoa.Columns["Ma"].HeaderText = "Mã";
                DgrHangHoa.Columns["Ten"].HeaderText = "Tên";
                DgrHangHoa.Columns["GiaBia"].HeaderText = "Giá bán lẻ";
                DgrHangHoa.Columns["GiaBia"].DefaultCellStyle.Format = "0";
                for (int c = 0; c < DgrHangHoa.ColumnCount; c++)
                {
                    if ((DgrHangHoa.Columns[c].Name == "Ma") || (DgrHangHoa.Columns[c].Name == "Ten") || (DgrHangHoa.Columns[c].Name == "GiaBia"))
                    {
                        DgrHangHoa.Columns[c].Visible = true;
                    }
                    else
                    {
                        DgrHangHoa.Columns[c].Visible = false;
                    }
                }

                txtFindMa.Enabled = true;
                TxtFindName.Enabled = true;
                cmbDoiTuong.Enabled = true;
                dtNgayHoaDon.Enabled = false;
                cmbPhieuNhap.Enabled = false;
            }
            else
            {
                txtFindMa.Enabled = false;
                TxtFindName.Enabled = false;
                cmbDoiTuong.Enabled = false;
                dtNgayHoaDon.Enabled = true;
                cmbPhieuNhap.Enabled = true;
            }
        }

        private void RdoTheoPhieuNhap_CheckedChanged(object sender, EventArgs e)
        {
            if (RdoTheoPhieuNhap.Checked)
                SearhTheoHoaDon();
        
            FrmProgressBar.StartShowProgress();
            SqlConnection con = new SqlConnection(GeneralLibs.LocalSettings.ConnectString);
            try
            {
                con.Open();
                SqlCommand cmd = con.CreateCommand();
                txtFindMa.Text = "";
                TxtFindName.Text = "";

                if (cmbPhieuNhap.SelectedValue != null)
                {
                    //Hiện thuốc theo hóa đơn, nhưng phiếu nhập k in được nên phải sửa

                    //cmd.CommandText = string.Format(
                    //           "SELECT B.Ma, B.Ten, B.GiaBia, A.Value1 AS SoLuong, D.Ten 'TenNCC'\n" +
                    //           "FROM KhoanMucChungTu A INNER JOIN VatTuHangHoa B ON A.VatTuHangHoa1ID = B.ID \n" +
                    //           "    INNER JOIN ChungTu C ON A.ChungTuID = C.ChungTuID \n" +
                    //           "    INNER JOIN DoiTuongNghiepVu D ON D.ID = C.DoiTuongNghiepVu1ID \n" +
                    //           "WHERE A.ChungTuID IN \n" +
                    //           "(  \n" +
                    //           "    SELECT ChungTuID \n" +
                    //           "    FROM ChungTu \n" +
                    //           "    WHERE ChungTuGocID = '{2}' \n" +
                    //           ") \n" +
                    //           "ORDER BY A.ThuTuKhoanMucTrongChungTu",
                    //           txtFindMa.Text, TxtFindName.Text, cmbPhieuNhap.SelectedValue
                    //           );

                    // Hiện thuốc phiếu nhập
                    cmd.CommandText = string.Format(
                               "SELECT B.Ma, B.Ten, B.GiaBia, A.Value1 AS SoLuong, D.Ten 'TenNCC'\n" +
                               "FROM KhoanMucChungTu A INNER JOIN VatTuHangHoa B ON A.VatTuHangHoa1ID = B.ID \n" +
                               "    INNER JOIN ChungTu C ON A.ChungTuID = C.ChungTuID \n" +
                               "    INNER JOIN DoiTuongNghiepVu D ON D.ID = C.DoiTuongNghiepVu1ID \n" +
                               "WHERE A.ChungTuID = '{2}' \n" +
                               "ORDER BY A.ThuTuKhoanMucTrongChungTu",
                               txtFindMa.Text, TxtFindName.Text, cmbPhieuNhap.SelectedValue
                               );

                    SqlDataAdapter da = new SqlDataAdapter(cmd);
                    DataSet ds = new DataSet();
                    da.Fill(ds);
                    DgrHangHoa.DataSource = ds.Tables[0].DefaultView;
                    DgrHangHoa.Columns["GiaBia"].HeaderText = "Giá bán lẻ";
                    DgrHangHoa.Columns["GiaBia"].DefaultCellStyle.Format = "0";
                    DgrHangHoa.Columns["Ma"].HeaderText = "Mã";
                    DgrHangHoa.Columns["Ten"].HeaderText = "Tên";
                    DgrHangHoa.Columns["SoLuong"].HeaderText = "Số lượng";
                    DgrHangHoa.Columns["SoLuong"].DefaultCellStyle.Format = "0";
                    DgrHangHoa.Columns["TenNCC"].HeaderText = "Tên nhà cung cấp";
                    DgrHangHoa.Columns["TenNCC"].Width = 250;

                    cmd.CommandText = string.Format("SELECT DoiTuongNghiepVu1ID " +
                                                    "FROM ChungTu " +
                                                    "WHERE ChungTuID = '{0}'",
                                                    cmbPhieuNhap.SelectedValue);
                    SqlDataReader dr = cmd.ExecuteReader();
                    if (dr.Read())
                    {
                        cmbDoiTuong.EditValue = (Guid)dr["DoiTuongNghiepVu1ID"];
                    }
                    dr.Close();
                }
                DgrHangHoa.DataSource = null;
            }
            catch (Exception ex)
            {
                BasicForms.FrmExceptionNotifier.ShowAndLog(ex);
            }
            finally
            {
                con.Close();
            }
            FrmProgressBar.FinishShowProgress();

            txtFindMa.Enabled = true;
            TxtFindName.Enabled = true;

        }

        private void dateTimePicker1_ValueChanged(object sender, EventArgs e)
        {
            if(RdoTheoPhieuNhap.Checked)
                SearhTheoHoaDon();
        }

        private void SearhTheoHoaDon()
        {
            FrmProgressBar.StartShowProgress();
            try
            {
                DieuKienTimKiemChungTu dkTimKiem = new DieuKienTimKiemChungTu();
                DateTime today = dtNgayHoaDon.Value;
                dkTimKiem.TuNgay = new NullableDate(new DateTime(today.Year, today.Month, today.Day, 0, 0, 0));
                dkTimKiem.DenNgay = new NullableDate(new DateTime(today.Year, today.Month, today.Day, 23, 59, 59));
                dkTimKiem.LoaiChungTu = DanhMucLoaiChungTu.Instance.GetByMa("PhieuNhapKho");
                DanhSachChungTu dsHoaDonMua = new DanhSachChungTu();
                dsHoaDonMua.LoadFromDB(dkTimKiem.BuildSqlStatement(1000, 1));
                cmbPhieuNhap.DataSource = dsHoaDonMua.DataTable;
                cmbPhieuNhap.DisplayMember = "So";
                cmbPhieuNhap.ValueMember = "ChungTuID";
            }
            catch (SqlException sqlEx)
            {
                throw new CustomException(CustomException.GetSqlExceptionMessage(sqlEx));
            }
            catch (Exception ex)
            {
                if (ex is CustomException) throw ex;
                else
                {
                    throw new Exception(ex.Message);
                }
            }
            FrmProgressBar.FinishShowProgress();
        }

        //private void CbPaperStyle_SelectedIndexChanged(object sender, EventArgs e)
        //{
        //    switch (CbPaperStyle.SelectedIndex)
        //    {
        //        case 0:
        //            {
        //                cPrinterWidth = 106 * 56.7; //' 106 mm (x 56.7 twip)
        //                cPrinterHeight = (73 * 56.7); //'4479 '79 mm
        //                break;
        //            }
        //        case 1:
        //            {
        //                cPrinterWidth = 6067;//' 107 mm (x 56.7 twip)
        //                cPrinterHeight = 5670; //'100 mm
        //                break;
        //            }
        //        case 2:
        //            {
        //                cPrinterWidth = 5953; //' 105 mm (x 56.7 twip)
        //                cPrinterHeight = 8788; //'155 mm
        //                break;
        //            }
        //        case 3:
        //            {
        //                cPrinterWidth = 11907;//' = 210 mm
        //                cPrinterHeight = 16840;// '297 mm
        //                break;
        //            }              
        //    }
        //    //CbX.SelectedIndex = Convert.ToInt32(cPrinterWidth / MyBarCode.Width - 1);  
        //    //CbX.SelectedIndex = Convert.ToInt32((int)cPrinterWidth /(int)1815 )-1;           
        //     //CbY.SelectedIndex = Convert.ToInt32(cPrinterHeight / (LbBottom.Top + LbBottom.Height - LbTop.Top) - 1);
        //    //CbY.SelectedIndex = Convert.ToInt32((int)(cPrinterHeight) / (int)(1155))-1 ;
        //    // ColsPerPage = CbX.SelectedIndex+1 ;
        //    // RowsPerPage = CbY.SelectedIndex+1 ;
        //}

        //private void CbY_SelectedIndexChanged(object sender, EventArgs e)
        //{
        //    RowsPerPage = CbY.SelectedIndex + 1;
        //}

        //private void CbX_SelectedIndexChanged(object sender, EventArgs e)
        //{
        //    ColsPerPage = CbX.SelectedIndex + 1;
        //}
       
        private void DgrInHang_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            if (DgrInHang.CurrentRow.Index != DgrInHang.RowCount-1)
            {
                try {
                    TxtBarCode.Text = DgrInHang[0, DgrInHang.CurrentRow.Index].Value.ToString();
                    TxtBookName.Text = DgrInHang[1, DgrInHang.CurrentRow.Index].Value.ToString();
                    if (TxtBarCode.Text != "") TxtTopText.Text = DanhMucVatTuHangHoa.GetByMa(TxtBarCode.Text.ToString()).TenNganGon;
                    TxtBottomText.Text = string.Format("{0:0,0}", Decimal.Parse((DgrInHang[2, DgrInHang.CurrentRow.Index].Value.ToString())));
                    //LbBottom.Text = string.Format("{0:0,0}", Decimal.Parse((DgrInHang[2, DgrInHang.CurrentRow.Index].Value.ToString())));
                    //LbTop.Text = DgrInHang[1, DgrInHang.CurrentRow.Index].Value.ToString();
                    //if (numSoLuongIn.Text == "")
                    //{
                    //    numSoLuongIn.Value = 1;
                    //}
                    //else
                    //{
                    //    numSoLuongIn.Value =  Convert.ToInt32(DgrInHang[3, DgrInHang.CurrentRow.Index].Value);
                    //}
                }
                catch (Exception ex)
                {
                    BasicForms.FrmExceptionNotifier.ShowAndLog(ex);
                }
            }
        }

        private void BtExit_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            FrmProgressBar.StartShowProgress();
            SqlConnection con = new SqlConnection(GeneralLibs.LocalSettings.ConnectString);
            try
            {
                con.Open();
                SqlCommand cmd = con.CreateCommand();
                txtFindMa.Text = "";
                TxtFindName.Text = "";
                if (cmbPhieuNhap.SelectedValue is Guid)
                {
                    //Hiện thuốc theo hóa đơn, nhưng phiếu nhập k in được nên phải sửa

                    //cmd.CommandText = string.Format(
                    //           "SELECT B.Ma, B.Ten, B.GiaBia, A.Value1 AS SoLuong, D.Ten 'TenNCC'\n" +
                    //           "FROM KhoanMucChungTu A INNER JOIN VatTuHangHoa B ON A.VatTuHangHoa1ID = B.ID \n" +
                    //           "    INNER JOIN ChungTu C ON A.ChungTuID = C.ChungTuID \n" +
                    //           "    INNER JOIN DoiTuongNghiepVu D ON D.ID = C.DoiTuongNghiepVu1ID \n" +
                    //           "WHERE A.ChungTuID IN \n" +
                    //           "(  \n" +
                    //           "    SELECT ChungTuID \n" +
                    //           "    FROM ChungTu \n" +
                    //           "    WHERE ChungTuGocID = '{2}' \n" +
                    //           ") \n" +
                    //           "ORDER BY A.ThuTuKhoanMucTrongChungTu",
                    //           txtFindMa.Text, TxtFindName.Text, cmbPhieuNhap.SelectedValue
                    //           );

                    // Hiện thuốc phiếu nhập
                    cmd.CommandText = string.Format(
                               "SELECT B.Ma, B.Ten, B.GiaBia, A.Value1 AS SoLuong, D.Ten 'TenNCC'\n" +
                               "FROM KhoanMucChungTu A INNER JOIN VatTuHangHoa B ON A.VatTuHangHoa1ID = B.ID \n" +
                               "    INNER JOIN ChungTu C ON A.ChungTuID = C.ChungTuID \n" +
                               "    INNER JOIN DoiTuongNghiepVu D ON D.ID = C.DoiTuongNghiepVu1ID \n" +
                               "WHERE A.ChungTuID = '{2}' \n" +
                               "ORDER BY A.ThuTuKhoanMucTrongChungTu",
                               txtFindMa.Text, TxtFindName.Text, cmbPhieuNhap.SelectedValue
                               );

                    SqlDataAdapter da = new SqlDataAdapter(cmd);
                    DataSet ds = new DataSet();
                    da.Fill(ds);
                    DgrHangHoa.DataSource = ds.Tables[0].DefaultView;
                    DgrHangHoa.Columns["GiaBia"].HeaderText = "Giá bán lẻ";
                    DgrHangHoa.Columns["GiaBia"].DefaultCellStyle.Format = "0";
                    DgrHangHoa.Columns["Ma"].HeaderText = "Mã";
                    DgrHangHoa.Columns["Ten"].HeaderText = "Tên";
                    DgrHangHoa.Columns["SoLuong"].HeaderText = "Số lượng";
                    DgrHangHoa.Columns["SoLuong"].DefaultCellStyle.Format = "0";
                    DgrHangHoa.Columns["TenNCC"].HeaderText = "Tên nhà cung cấp";

                    DgrHangHoa.Columns["GiaBia"].Width = 80;
                    DgrHangHoa.Columns["Ten"].Width = 200;
                    DgrHangHoa.Columns["SoLuong"].Width = 60;
                    DgrHangHoa.Columns["TenNCC"].Width = 250;

                    cmd.CommandText = string.Format("SELECT DoiTuongNghiepVu1ID " +
                                                    "FROM ChungTu " +
                                                    "WHERE ChungTuID = '{0}'",
                                                    cmbPhieuNhap.SelectedValue);
                    SqlDataReader dr = cmd.ExecuteReader();
                    if (dr.Read())
                    {
                        cmbDoiTuong.EditValue = (Guid)dr["DoiTuongNghiepVu1ID"];
                    }
                    dr.Close();
                }
            }
            catch (Exception ex)
            {
                BasicForms.FrmExceptionNotifier.ShowAndLog(ex);
            }
            finally
            {
                con.Close();
            }
            FrmProgressBar.FinishShowProgress();
        }

        private void comboBox2_SelectedIndexChanged(object sender, EventArgs e)
        {
        }

        private void TxtFindName_TextChanged(object sender, EventArgs e)
        {
            SqlConnection con = new SqlConnection(GeneralLibs.LocalSettings.ConnectString);
            try
            {
                con.Open();
                SqlCommand cmd = con.CreateCommand();

                if (RdoTheoPhieuNhap.Checked)
                {
                    cmd.CommandText = string.Format(
                           "SELECT B.Ma, B.Ten, B.GiaBia, A.Value1 AS SoLuong, D.Ten 'TenNCC'\n" +
                           "FROM KhoanMucChungTu A INNER JOIN VatTuHangHoa B ON A.VatTuHangHoa1ID = B.ID \n" +
                           "    INNER JOIN ChungTu C ON A.ChungTuID = C.ChungTuID \n" +
                           "    INNER JOIN DoiTuongNghiepVu D ON D.ID = C.DoiTuongNghiepVu1ID \n" +
                           "WHERE B.Ma like N'%{0}%' AND B.Ten like N'%{1}%' AND A.ChungTuID IN \n" +
                           "(  \n" +
                           "    SELECT ChungTuID \n" +
                           "    FROM ChungTu \n" +
                           "    WHERE ChungTuGocID = '{2}' \n" +
                           ") \n" +
                           "ORDER BY A.ThuTuKhoanMucTrongChungTu",
                           txtFindMa.Text, TxtFindName.Text, cmbPhieuNhap.SelectedValue
                           );
                }
                else
                {
                    cmd.CommandText = string.Format(
                                "SELECT Ma, Ten, GiaBia                     \n" +
                                "FROM VatTuHangHoa                          \n" +
                                "WHERE Ma like N'%{0}%' AND Ten like N'%{1}%'   \n",
                                txtFindMa.Text, TxtFindName.Text
                                );
                }
                SqlDataAdapter da = new SqlDataAdapter(cmd);
                DataSet ds = new DataSet();

                da.Fill(ds);
                DgrHangHoa.DataSource = ds.Tables[0].DefaultView;
                DgrHangHoa.Columns["GiaBia"].HeaderText = "Giá bán lẻ";
                DgrHangHoa.Columns["GiaBia"].DefaultCellStyle.Format = "0";
                DgrHangHoa.Columns["Ma"].HeaderText = "Mã";
                DgrHangHoa.Columns["Ten"].HeaderText = "Tên";
                if (RdoTheoPhieuNhap.Checked)
                {
                    DgrHangHoa.Columns["TenNCC"].HeaderText = "Tên nhà cung cấp";
                    DgrHangHoa.Columns["TenNCC"].Width = 250;
                }
                DgrHangHoa.Columns["GiaBia"].Width = 80;
                DgrHangHoa.Columns["Ten"].Width = 200;
                //DgrHangHoa.Columns["SoLuong"].Width = 60;
                
            }
            catch (Exception ex)
            {
                BasicForms.FrmExceptionNotifier.ShowAndLog(ex);
            }
            finally
            {
                con.Close();
            }
        }

        private void txtFindMa_TextChanged(object sender, EventArgs e)
        {
            SqlConnection con = new SqlConnection(GeneralLibs.LocalSettings.ConnectString);
            try
            {
                con.Open();
                SqlCommand cmd = con.CreateCommand();

                if (RdoTheoPhieuNhap.Checked)
                {
                    cmd.CommandText = string.Format(
                           "SELECT B.Ma, B.Ten, B.GiaBia, A.Value1 AS SoLuong, D.Ten 'TenNCC'\n" +
                           "FROM KhoanMucChungTu A INNER JOIN VatTuHangHoa B ON A.VatTuHangHoa1ID = B.ID \n" +
                           "    INNER JOIN ChungTu C ON A.ChungTuID = C.ChungTuID \n" +
                           "    INNER JOIN DoiTuongNghiepVu D ON D.ID = C.DoiTuongNghiepVu1ID \n" +
                           "WHERE B.Ma like N'%{0}%' AND B.Ten like N'%{1}%' AND A.ChungTuID IN \n" +
                           "(  \n" +
                           "    SELECT ChungTuID \n" +
                           "    FROM ChungTu \n" +
                           "    WHERE ChungTuGocID = '{2}' \n" +
                           ") \n" +
                           "    ORDER BY A.ThuTuKhoanMucTrongChungTu",
                           txtFindMa.Text, TxtFindName.Text, cmbPhieuNhap.SelectedValue
                           );
                }
                else
                {
                    cmd.CommandText = string.Format(
                                "SELECT Ma, Ten, GiaBia                     \n" +
                                "FROM VatTuHangHoa                          \n" +
                                "WHERE Ma like N'%{0}%' AND Ten like N'%{1}%'   \n",
                                txtFindMa.Text, TxtFindName.Text
                                );
                }
                SqlDataAdapter da = new SqlDataAdapter(cmd);
                DataSet ds = new DataSet();

                da.Fill(ds);
                DgrHangHoa.DataSource = ds.Tables[0].DefaultView;
                DgrHangHoa.Columns["GiaBia"].HeaderText = "Giá bán lẻ";
                DgrHangHoa.Columns["GiaBia"].DefaultCellStyle.Format = "0";
                DgrHangHoa.Columns["Ma"].HeaderText = "Mã";
                DgrHangHoa.Columns["Ten"].HeaderText = "Tên";
                if (RdoTheoPhieuNhap.Checked)
                {
                    DgrHangHoa.Columns["TenNCC"].HeaderText = "Tên nhà cung cấp";
                    DgrHangHoa.Columns["TenNCC"].Width = 250;
                }
                DgrHangHoa.Columns["GiaBia"].Width = 80;
                DgrHangHoa.Columns["Ten"].Width = 200;
                //DgrHangHoa.Columns["SoLuong"].Width = 60;
            }
            catch (Exception ex)
            {
                BasicForms.FrmExceptionNotifier.ShowAndLog(ex);
            }
            finally
            {
                con.Close();
            }
        }

        private void DgrHangHoa_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            if (!(cmbDoiTuong.EditValue is Guid) || (Guid)cmbDoiTuong.EditValue == Guid.Empty)
            {
                MessageBox.Show("Bạn chưa chọn nhà cung cấp thuốc");
                cmbDoiTuong.Focus();
            }
            else
            {
                if (RdoTheoPhieuNhap.Checked)
                {
                    foreach (DataGridViewRow r in DgrHangHoa.SelectedRows)
                    {
                        dsPrinBarcode.ChoosedHang.Rows.Add(DgrHangHoa["Ma", r.Index].Value, DgrHangHoa["Ten", r.Index].Value, DgrHangHoa["GiaBia", r.Index].Value, DgrHangHoa["SoLuong", r.Index].Value,
                                            DanhMucDoiTuongNghiepVu.Instance.GetByID((Guid)cmbDoiTuong.EditValue).Ma);
                    }
                }
                else
                {
                    foreach (DataGridViewRow r in DgrHangHoa.SelectedRows)
                    {
                        dsPrinBarcode.ChoosedHang.Rows.Add(DgrHangHoa["Ma", r.Index].Value, DgrHangHoa["Ten", r.Index].Value, DgrHangHoa["GiaBia", r.Index].Value, //numSoLuongIn.Value,
                                            DanhMucDoiTuongNghiepVu.Instance.GetByID((Guid)cmbDoiTuong.EditValue).Ma);
                    }
                }
            }
        }

        private void btnAdd_Click(object sender, EventArgs e)
        {
            try
            {
                //DgrInHang.ColumnCount = 5;
                string maNCC = "";
                if ((cmbDoiTuong.EditValue is Guid) && (Guid)cmbDoiTuong.EditValue != Guid.Empty)
                {
                    maNCC = DanhMucDoiTuongNghiepVu.Instance.GetByID((Guid)cmbDoiTuong.EditValue).Ma;
                }

                int count = DgrHangHoa.SelectedRows.Count;
                if (RdoTheoPhieuNhap.Checked) //Chọn từ phiếu nhập
                {
                    for (int i = count-1; i >=0; i--)
                    {
                        //convert decimal -> int de hien cho chuan
                        int giaBia = Convert.ToInt32(DgrHangHoa["GiaBia", DgrHangHoa.SelectedRows[i].Index].Value);
                        int soLuong = Convert.ToInt32(DgrHangHoa["SoLuong", DgrHangHoa.SelectedRows[i].Index].Value);
                        string maHang = DgrHangHoa["Ma", DgrHangHoa.SelectedRows[i].Index].Value.ToString();
                        VatTuHangHoa vthh = DanhMucVatTuHangHoa.GetByMa(maHang);
                        
                        //Nếu là số lượng lấy từ phiếu nhập thì cần chia số tem tương ứng với số lượng để tự động ra số tem
                        int soLuongTem = 1;
                        if (soLuong % vthh.HeSoInMaVach == 0)
                            soLuongTem = (soLuong / vthh.HeSoInMaVach);
                        else
                            soLuongTem = (soLuong / vthh.HeSoInMaVach) + 1;
                        dsPrinBarcode.ChoosedHang.Rows.Add(DgrHangHoa["Ma", DgrHangHoa.SelectedRows[i].Index].Value, DgrHangHoa["Ten", DgrHangHoa.SelectedRows[i].Index].Value, giaBia, soLuongTem,//DgrHangHoa["GiaBia", DgrHangHoa.SelectedRows[i].Index].Value, DgrHangHoa["SoLuong", DgrHangHoa.SelectedRows[i].Index].Value,
                                                    maNCC);
                    }
                }
                else
                {
                    for (int i = count-1; i >= 0; i--)
                    {
                        //Nếu là số lượng in thêm thì cho thiếu bao nhiêu in bấy nhiêu
                        bool added = false;
                        int giaBia = Convert.ToInt32(DgrHangHoa["GiaBia", DgrHangHoa.SelectedRows[i].Index].Value);
                        //int soLuong = Convert.ToInt32(numSoLuongIn.Value);
                        //Điền số lượng mặc định = 1
                        foreach (DataRow r in dsPrinBarcode.ChoosedHang.Rows)
                        {
                            //thuốc đã có thì tăng số lượng lên thôi
                            if (r["Mã hàng"].ToString() == DgrHangHoa["Ma", DgrHangHoa.SelectedRows[i].Index].Value.ToString())
                            {
                                r["Số lượng in"] = Convert.ToInt32(r["Số lượng in"].ToString()) + 1;
                                added = true;
                            }
                        }
                        if(added == false)
                            dsPrinBarcode.ChoosedHang.Rows.Add(DgrHangHoa["Ma", DgrHangHoa.SelectedRows[i].Index].Value, DgrHangHoa["Ten", DgrHangHoa.SelectedRows[i].Index].Value,
                                    giaBia, 1, maNCC);
                    }
                   
                }
            }
            catch (Exception ex)
            {
                BasicForms.FrmExceptionNotifier.ShowAndLog(ex);
            }
        }

        private Image GenBarCodeImage(string ma, int width, int height)     //Sinh ảnh mã vạch từ chuỗi mã. Dùng thư viện BarcodeLib.
        {
            try
            {
                BarcodeLib.Barcode barcode = new BarcodeLib.Barcode();
                barcode.Alignment = AlignmentPositions.CENTER;
                barcode.IncludeLabel = false;
                Image image = null;
                if(ma.Length == 13)
                    image = barcode.Encode(TYPE.EAN13, ma, Color.Black, Color.White, width, height);
                else
                    image = barcode.Encode(TYPE.CODE128, ma, Color.Black, Color.White, width, height);
                return image;
            }
            catch (Exception ex)
            {
                return null;
            }
        }

        private void PrintA4()  //In A4 tự dọc. Hiện đang dùng tại NS Bách Khoa
        {

            try
            {
                if (DgrInHang.RowCount == 0)
                {
                    MessageBox.Show("Bạn chưa chọn mặt hàng để in mã vạch");
                }
                else
                {
                    DsPrintBarCode ds = new DsPrintBarCode();
                    DataRow row = null;
                    int index = 0;

                    for (int r = 0; r < DgrInHang.RowCount - 1; r++)//moi loai tem
                    {
                        int soLuong = Convert.ToInt32(DgrInHang[3, r].Value);
                        string strTen = "";
                        string strMa = (string)(DgrInHang[0, r].Value);
                        if (!chkInTheoTenNganGon.Checked) strTen = (DgrInHang[1, r].Value).ToString();
                        else
                        {
                            try
                            {
                                strTen = DanhMucVatTuHangHoa.GetByMa(strMa).TenNganGon;
                            }
                            catch (Exception ex)
                            {
                                strTen = (DgrInHang[1, r].Value).ToString();
                            }
                        }
                        if (strTen == "") strTen = (DgrInHang[1, r].Value).ToString();

                        if (strTen.Length > 22)
                        {
                            strTen = strTen.Substring(0, 19) + "...";
                        }

                        for (int c = 0; c < soLuong; c++)//moi tem cua mot loai
                        {
                            if (index == 0)
                            {
                                row = ds.DataTable1.NewRow();
                                ds.DataTable1.Rows.Add(row);
                            }
                            index++;

                            System.IO.MemoryStream ms = new System.IO.MemoryStream();
                            Image image = GenBarCodeImage((string)(DgrInHang[0, r].Value), BARCODE_WIDTH, BARCODE_HEIGHT);
                            if (image != null) image.Save(ms, System.Drawing.Imaging.ImageFormat.Bmp);

                            switch (index)
                            {
                                case 1:
                                    row["Image1"] = ms.ToArray();
                                    row["Ten1"] = strTen;
                                    row["Ma1"] = strMa;
                                    row["Gia1"] = string.Format("{0:0,0}", Decimal.Parse((DgrInHang[2, r].Value.ToString()))) + " đ";
                                    row["ChungLoai1"] = ((DgrInHang[4, r].Value.ToString()));
                                    break;
                                case 2:
                                    row["Image2"] = ms.ToArray();
                                    row["Ten2"] = strTen;
                                    row["Ma2"] = strMa;
                                    row["Gia2"] = string.Format("{0:0,0}", Decimal.Parse((DgrInHang[2, r].Value.ToString()))) + " đ";
                                    row["ChungLoai2"] = ((DgrInHang[4, r].Value.ToString()));
                                    break;
                                case 3:
                                    row["Image3"] = ms.ToArray();
                                    row["Ten3"] = strTen;
                                    row["Ma3"] = strMa;
                                    row["Gia3"] = string.Format("{0:0,0}", Decimal.Parse((DgrInHang[2, r].Value.ToString()))) + " đ";
                                    row["ChungLoai3"] = ((DgrInHang[4, r].Value.ToString()));
                                    //index = 0;
                                    break;
                                case 4:
                                    row["Image4"] = ms.ToArray();
                                    row["Ten4"] = strTen;
                                    row["Ma4"] = strMa;
                                    row["Gia4"] = string.Format("{0:0,0}", Decimal.Parse((DgrInHang[2, r].Value.ToString()))) + " đ";
                                    row["ChungLoai4"] = ((DgrInHang[4, r].Value.ToString()));
                                    break;
                                case 5:
                                    row["Image5"] = ms.ToArray();
                                    row["Ten5"] = strTen;
                                    row["Ma5"] = strMa;
                                    row["Gia5"] = string.Format("{0:0,0}", Decimal.Parse((DgrInHang[2, r].Value.ToString()))) + " đ";
                                    row["ChungLoai5"] = ((DgrInHang[4, r].Value.ToString()));
                                    break;
                                case 6:
                                    row["Image6"] = ms.ToArray();
                                    row["Ten6"] = strTen;
                                    row["Ma6"] = strMa;
                                    row["Gia6"] = string.Format("{0:0,0}", Decimal.Parse((DgrInHang[2, r].Value.ToString()))) + " đ";
                                    row["ChungLoai6"] = ((DgrInHang[4, r].Value.ToString()));
                                    index = 0;
                                    break;
                            }
                        }
                    }

                    RptBarcodeA4 report = new RptBarcodeA4();
                    report.SetDataSource(ds);

                    FrmShowReport frm = new FrmShowReport();
                    frm.crystalReportViewer1.ReportSource = report;
                    frm.Show();
                }
            }
            catch (Exception ex)
            {
                BasicForms.FrmExceptionNotifier.ShowAndLog(ex);
            }
        }
        private void PrintThreeColumnBarCode()
        {
            try
            {
                if (DgrInHang.RowCount == 0)
                {
                    MessageBox.Show("Bạn chưa chọn mặt hàng để in mã vạch");
                }
                else
                {
                    DsPrintBarCode ds = new DsPrintBarCode();
                    DataRow row = null;
                    int index = 0;

                    for (int r = 0; r < DgrInHang.RowCount - 1; r++)//moi loai tem
                    {
                        int soLuong = Convert.ToInt32(DgrInHang[3, r].Value);
                        string strTen = "";
                        string strMa = (string)(DgrInHang[0, r].Value);
                        if (!chkInTheoTenNganGon.Checked) strTen = (DgrInHang[1, r].Value).ToString();
                        else
                        {
                            try
                            {
                                strTen = DanhMucVatTuHangHoa.GetByMa(strMa).TenNganGon;
                            }
                            catch (Exception ex)
                            {
                                strTen = (DgrInHang[1, r].Value).ToString();
                            }
                        }
                        if (strTen == "") strTen = (DgrInHang[1, r].Value).ToString();

                        if (strTen.Length > 22)
                        {
                            strTen = strTen.Substring(0, 19) + "...";
                        }

                        for (int c = 0; c < soLuong; c++)//moi tem cua mot loai
                        {
                            if (index == 0)
                            {
                                row = ds.DataTable1.NewRow();
                                ds.DataTable1.Rows.Add(row);
                            }
                            index++;

                            System.IO.MemoryStream ms = new System.IO.MemoryStream();
                            Image image = GenBarCodeImage((string)(DgrInHang[0, r].Value), BARCODE_WIDTH, BARCODE_HEIGHT);
                            if (image != null) image.Save(ms, System.Drawing.Imaging.ImageFormat.Bmp);

                            switch (index)
                            {
                                case 1:
                                    row["Image1"] = ms.ToArray();
                                    row["Ten1"] = strTen;
                                    row["Ma1"] = strMa;
                                    row["Gia1"] = string.Format("{0:0,0}", Decimal.Parse((DgrInHang[2, r].Value.ToString()))) + " đ";
                                    row["ChungLoai1"] = ((DgrInHang[4, r].Value.ToString()));
                                    break;
                                case 2:
                                    row["Image2"] = ms.ToArray();
                                    row["Ten2"] = strTen;
                                    row["Ma2"] = strMa;
                                    row["Gia2"] = string.Format("{0:0,0}", Decimal.Parse((DgrInHang[2, r].Value.ToString()))) + " đ";
                                    row["ChungLoai2"] = ((DgrInHang[4, r].Value.ToString()));
                                    break;
                                case 3:
                                    row["Image3"] = ms.ToArray();
                                    row["Ten3"] = strTen;
                                    row["Ma3"] = strMa;
                                    row["Gia3"] = string.Format("{0:0,0}", Decimal.Parse((DgrInHang[2, r].Value.ToString()))) + " đ";
                                    row["ChungLoai3"] = ((DgrInHang[4, r].Value.ToString()));
                                    index = 0;
                                    break;
                            }
                        }
                    }

                    CrystalDecisions.CrystalReports.Engine.ReportClass report = null;
                    string tenDoanhNghiepVietHoa = Config.TenDoanhNghiep.ToUpper();
                    Store store = DanhMucStore.Instance.GetByStoreID(Config.StoreID);
                    report = new RptBarcode3Column();
                    report.SetDataSource(ds);

                    FrmShowReport frm = new FrmShowReport();
                    frm.crystalReportViewer1.ReportSource = report;
                    frm.Show();
                }
            }
            catch (SqlException sqlEx)
            {
                throw new CustomException(CustomException.GetSqlExceptionMessage(sqlEx));
            }
            catch (Exception ex)
            {
                if (ex is CustomException) throw ex;
                else
                {
                    throw new Exception(ex.Message);
                }
            }

        }   //In 3 cột chuẩn theo mãu máy in mã vạch chuyên dụng. Ninh Bình đang sử dụng

        // in chuyên dụng
        private void buttonInChuyenDung_Click(object sender, EventArgs e)
        {
            try
            {
                if(Config.StoreID is int && Config.StoreID > 0)
                {
                    PrintThreeColumnBarCode();
                }
                else
                {
                    PrintThreeColumnBarCode();
                }
                 //if(Config.StoreID)
            }
            catch (Exception ex)
            {
                BasicForms.FrmExceptionNotifier.ShowAndLog(ex);
            }
        }
        // in A4
        private void btnInA4_Click(object sender, EventArgs e)
        {
            try
            {
                PrintA4();
            }
            catch (Exception ex)
            {
                BasicForms.FrmExceptionNotifier.ShowAndLog(ex);
            }
        }

        private void cmbNhomHang_EditValueChanged(object sender, EventArgs e)
        {
            FrmProgressBar.StartShowProgress();
            SqlConnection con = new SqlConnection(GeneralLibs.LocalSettings.ConnectString);
            try
            {
                con.Open();
                SqlCommand cmd = con.CreateCommand();
                txtFindMa.Text = "";
                TxtFindName.Text = "";
                RdoTheoPhieuNhap.Checked = false;
                RdoToanBoKhoHang.Checked = true;

                cmd.CommandText = string.Format("SELECT * FROM VatTuHangHoa WHERE NhomVatTuHangHoaID = '{0}'", cmbNhomHang.EditValue.ToString());

                SqlDataAdapter da = new SqlDataAdapter(cmd);
                DataSet ds = new DataSet();
                da.Fill(ds);
                DgrHangHoa.DataSource = ds.Tables[0].DefaultView;
                DgrHangHoa.Columns["GiaBia"].HeaderText = "Giá bán lẻ";
                DgrHangHoa.Columns["GiaBia"].DefaultCellStyle.Format = "0";
                DgrHangHoa.Columns["Ma"].HeaderText = "Mã";
                DgrHangHoa.Columns["Ten"].HeaderText = "Tên";
                DgrHangHoa.Columns["GiaBia"].Width = 80;
                DgrHangHoa.Columns["Ten"].Width = 200;
            }
            catch (Exception ex)
            {
                BasicForms.FrmExceptionNotifier.ShowAndLog(ex);
            }
            finally
            {
                con.Close();
            }
            FrmProgressBar.FinishShowProgress();
        }
    }
}

